package config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import pojo.Configuration;
import pojo.MappedStatement;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public Configuration parConfig(InputStream inputStream) throws DocumentException {

        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(inputStream);

        Element rootElement = read.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();

            String sqlType = element.getName();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlType(sqlType);

            String mappedKey = namespace+"."+id;
            configuration.getMappedStatementMap().put(mappedKey,mappedStatement);
        }

        return configuration;

    }
}
